//
//  PayPlugin.cpp
//  Unity-iPhone
//
//  Created by yutao on 14-1-2.
//
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "MePayment.h"


extern UIViewController *UnityGetGLViewController();

@interface PayPlugin : NSObject<PayCallBack>
{
	NSString *gameObjectName;
}
@end

@implementation PayPlugin

- (id)initWithGameObjectName:(const char *)gameObjectName_
{
	self = [super init];
    
	gameObjectName = [[NSString stringWithUTF8String:gameObjectName_] retain];
	return self;
}

- (void)dealloc
{
    [gameObjectName release];
	[super dealloc];
}

- (void)Pay:(const char *)commodityId{
    NSString *cId=[NSString stringWithUTF8String:commodityId];
    
    NSLog(@"%@",cId);
    //cId=@"com.quizrpg.add100";
    
    MePayment* payMent=[MePayment shared];
    payMent.callFunc=self;
    [payMent buyProduct:cId];
}

-(void) payResult:(int) result : (NSString *) identifier : (NSString *) receipt :(NSString *) reason{
    NSLog(@"购买完成:%d-%@",result,reason);
    
    NSArray *arr=[[NSArray  alloc] initWithObjects:[NSString stringWithFormat:@"%d",result],identifier,receipt,reason, nil ];
    
    NSError *error;
    NSData *registerData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *msg=[[[NSString alloc] initWithData:registerData encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"Register JSON:%@",msg);
    
    UnitySendMessage([gameObjectName UTF8String], "PayResult",[msg UTF8String]);

}

@end


extern "C" {
	void* _PayPlugin_Init(const char *gameObjectName);
    void  _PayPlugin_Pay(void *instance,const char *commodityId);

}

void* _PayPlugin_Init(const char *gameObjectName)
{
	id instance = [[PayPlugin alloc] initWithGameObjectName:gameObjectName];
	return (void *)instance;
}

void _PayPlugin_Pay(void *instance,const char *commodityId)
{
    PayPlugin *payPlugin = (PayPlugin *)instance;
    [payPlugin Pay:commodityId];

}

